package com.ruyuan.user.server.rpc;

import com.ruyuan.common.model.PageDTO;
import com.ruyuan.common.model.Response;
import com.ruyuan.user.api.OrganizationReadFacade;
import com.ruyuan.user.api.model.response.OrganizationBaseDTO;
import com.ruyuan.user.server.domain.model.Organization;
import com.ruyuan.user.server.domain.service.OrganizationDomainService;
import com.ruyuan.user.server.domain.service.request.PageQueryOrganizationParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xx
 */
@Service
public class OrganizationReadFacadeImpl implements OrganizationReadFacade {

    @Autowired
    private OrganizationDomainService organizationDomainService;

    @Override
    public Response<List<OrganizationBaseDTO>> queryAllChildren(Long orgId) {
        Organization organization = organizationDomainService.queryOrganizationById(orgId);
        List<OrganizationBaseDTO> dtos = innerQueryAllChildren(orgId, organization.getRootId());
        return Response.success(dtos);
    }

    private List<OrganizationBaseDTO> innerQueryAllChildren(Long orgId, Long rootOrgId) {
        PageQueryOrganizationParam param = new PageQueryOrganizationParam();
        param.setRootOrgId(rootOrgId);
        param.setParentId(orgId);
        param.setPageSize(Integer.MAX_VALUE);
        param.setCurrent(1);
        PageDTO<Organization> organizationPageDTO = organizationDomainService.queryOrganizationByCondition(param);
        if (CollectionUtils.isEmpty(organizationPageDTO.getData())) {
            return new ArrayList<>();
        }
        return organizationPageDTO.getData().stream().map(org -> {
            List<OrganizationBaseDTO> result = new ArrayList<>();
            OrganizationBaseDTO organizationBaseDTO = new OrganizationBaseDTO();
            BeanUtils.copyProperties(org, organizationBaseDTO);
            result.add(organizationBaseDTO);
            result.addAll(innerQueryAllChildren(org.getId(), rootOrgId));
            return result;
        }).flatMap(Collection::stream).collect(Collectors.toList());
    }

}
